package com.zxy.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 自定义 LocalDateTime 反序列化器
 */
public class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

    private static final DateTimeFormatter FORMATTER_WITHOUT_SECONDS = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    private static final DateTimeFormatter FORMATTER_WITH_SECONDS = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String dateStr = p.getText().trim();
        try {
            if (dateStr.length() == 16) { // "2025-09-10 12:00"
                return LocalDateTime.parse(dateStr, FORMATTER_WITHOUT_SECONDS);
            } else {
                return LocalDateTime.parse(dateStr, FORMATTER_WITH_SECONDS);
            }
        } catch (Exception e) {
            throw new RuntimeException("无法解析日期: " + dateStr, e);
        }
    }
}